package com.binsoft.ndtta;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TeamListAdapter extends BaseAdapter
{
	private static final String TAG = "TeamListAdapter";
	private Context mContext = null;
	private LayoutInflater mLayoutInflater = null;
	private ArrayList<String> mEntries = new ArrayList<String>();
	private int mDivision = 0;
	
	private OnClickListener mClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) 
		{
			String numberString = "";
			String emailAddr = "";
			
			boolean mailer = false;
			boolean dialer = false;
			boolean map = false;
			
			Log.i(TAG, "Id:" + v.getId() );
			
			if ( v.getId() == R.id.teamViewLandLine )
			{	
		   		TextView landLineField = ((TextView)v.findViewById(R.id.teamViewLandLine));
				numberString = landLineField.getText().toString();
				dialer = true;
			}
			else if ( v.getId() == R.id.teamViewMobile )
			{
		   		TextView mobileField = ((TextView)v.findViewById(R.id.teamViewMobile));
				numberString = mobileField.getText().toString();
				dialer = true;
			}
			else if ( v.getId() == R.id.teamViewWork )
			{
		   		TextView workField = ((TextView)v.findViewById(R.id.teamViewWork));
				numberString = workField.getText().toString();
				dialer = true;
			}
			else if ( v.getId() == R.id.teamViewEmail )
			{
		   		TextView emailField = ((TextView)v.findViewById(R.id.teamViewEmail));
				emailAddr = emailField.getText().toString();
				mailer = true;
			}
			else if ( v.getId() == R.id.teamViewMap )
			{
				map = true;
			}
			
			Intent intent = null;
			
			if ( dialer )
			{
				intent = new Intent( Intent.ACTION_DIAL, Uri.parse("tel:" + numberString) );
			}
			else if ( mailer )
			{
				// Setup a pending event for the email button
				final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
				emailIntent.setType("plain/text");
				emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{emailAddr});
				emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "NDTTA");
				intent = Intent.createChooser(emailIntent, "Email:");
			}
			else if ( map )
			{
				Integer selectedTeam = (Integer)v.getTag();
				
				Team team = Matches.getTeam( mDivision, selectedTeam.intValue() + 1);
				intent = new Intent( mContext, LocationView.class );
				intent.putExtra( Constants.LATITUDE_INTENT_EXTRA, team.latitude() );
				intent.putExtra( Constants.LONGITUDE_INTENT_EXTRA, team.longitude() );
			}
			if ( intent  != null )
			{
				mContext.startActivity( intent );
			}
		}
	};
	

	TeamListAdapter( Context context, ArrayList<String> teams, int division )
	{
		mContext = context;
		mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mEntries = teams;
		mDivision = division;
   	}
	
	@Override
	public int getCount()
	{
		return mEntries.size();
	}

	@Override
	public Object getItem(int position)
	{
		return mEntries.get( position );
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	private void setTextViewText( TextView view, TextView label, byte[] text, byte[] key )
	{
		byte[] decrypted = null;
		
		try
		{
			if ( null != text )
			{
				Log.i(TAG, "Key length:" + key.length );
				decrypted = Encryptor.decrypt(text, key );
			}
		}
		catch ( Exception e )
		{
			Log.e(TAG, "Failed to decrypt data");
		}
		
		if ( null == decrypted )
		{
			view.setVisibility( View.GONE );
			label.setVisibility( View.GONE );
		}
		else
		{
			view.setText( new String( decrypted ) );
		}
		
		// Setup the views click listener
		view.setOnClickListener(mClickListener);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		RelativeLayout itemView;
		
        if (convertView == null) 
        {                                        
    		itemView = (RelativeLayout) mLayoutInflater.inflate(
                    R.layout.team_view, parent, false);
        } 
        else 
        {
           itemView = (RelativeLayout) convertView;
        }
        
		// Setup the fields from the stored team
		Team team = Matches.getTeam(mDivision, position + 1 );

		if ( !team.name().isEmpty() )
		{
			// Show all the fields incase we are reusing a view
			for ( int index = 0 ; index < itemView.getChildCount() ; index++ )
			{
				itemView.getChildAt( index ).setVisibility(View.VISIBLE);
			}

			TeamContact contactDetails = team.contact();
			
	   		((TextView)itemView.findViewById(R.id.teamViewTeam)).setText( team.name() );
	   		setTextViewText((TextView)itemView.findViewById(R.id.teamViewContact),
	   						(TextView)itemView.findViewById(R.id.contactLabel),
   							contactDetails.encName(), contactDetails.key() );
	   		
	   		setTextViewText((TextView)itemView.findViewById(R.id.teamViewEmail), 
	   						(TextView)itemView.findViewById(R.id.emailLabel), 
	   						contactDetails.encEmail(), 
	   						contactDetails.key() );

	   		setTextViewText((TextView)itemView.findViewById(R.id.teamViewLandLine), 
	   						(TextView)itemView.findViewById(R.id.telephoneLabel), 
	   						contactDetails.encLandline(), 
	   						contactDetails.key() );

	   		setTextViewText((TextView)itemView.findViewById(R.id.teamViewWork), 
	   						(TextView)itemView.findViewById(R.id.workLabel), 
	   						contactDetails.encWork(), 
	   						contactDetails.key() );
	   		
	   		setTextViewText((TextView)itemView.findViewById(R.id.teamViewMobile), 
	   						(TextView)itemView.findViewById(R.id.mobileLabel),
	   						contactDetails.encMobile(), 
	   						contactDetails.key() );
	   		
	   		// Setup map button and assign the position as this corresponds to the team
	   		View mapButton = itemView.findViewById(R.id.teamViewMap);
	   		mapButton.setOnClickListener(mClickListener);
	   		mapButton.setTag( Integer.valueOf( position ) );
	   		
	   		((TextView)itemView.findViewById(R.id.teamViewHomeNight)).setText( Helpers.convertDayofWeek( team.homeNight() ) );
		}
		else
		{
			// No team so clear hide the view
			for ( int index = 0 ; index < itemView.getChildCount() ; index++ )
			{
				itemView.getChildAt( index ).setVisibility(View.GONE);
			}
	   		((TextView)itemView.findViewById(R.id.teamViewTeam)).setText( "No Team" );
			itemView.findViewById(R.id.teamViewTeam).setVisibility(View.VISIBLE );
		}

		return itemView;
	}

}
